package com.undsf.domainganker.chinaz;

import com.undsf.domainganker.DomainInfo;
import com.undsf.domainganker.Ganker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.undsf.domainganker.GankerException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Created by Arathi on 2015/4/24.
 */
public class ChinazGanker extends Ganker {
    public static final String WHOIS_URL_FORMAT = "http://whois.chinaz.com/?Domain=%s&isforceupdate=1";
    public static final String DELETED_URL = "http://del.chinaz.com/";
    public static final Pattern PATTERN_PAGE = Pattern.compile("\\u5171\\s*(\\d+)\\s*\\u9875"); //共\s*{\d+}\s*页
    public static final Pattern PATTERN_DATE = Pattern.compile("(\\d+)-(\\d+)\\u6708-(\\d+)");

    private static Map<String, Integer> DomainStatusDesc;

    static {
        DomainStatusDesc = new HashMap<String, Integer>();
        DomainStatusDesc.put("Delete", DomainInfo.DOMAIN_STATUS_DELETED);
        DomainStatusDesc.put("Pre-Release", DomainInfo.DOMAIN_STATUS_PRE_RELEASE);
    }

    private SearchConfig conf;
    private List<DomainInfo> domains;

    public ChinazGanker(){
        super();
        domains = new ArrayList<DomainInfo>();
    }

    @Override
    public boolean check(DomainInfo domain){
        String url = String.format(WHOIS_URL_FORMAT, domain.getDomainName());
        try{
            String html = httpClient.getRequest(url);
            Document doc = Jsoup.parse(html);
            Elements css_div_whois = doc.select(".div_whois");
            int divAmount = css_div_whois.size();
            //System.out.println("选取class为`div_whois`的节点，获取到" + divAmount + "个节点");
            if (divAmount==1){
                //两种情况
                Element div = css_div_whois.first();
                if (div.text().indexOf("该域名未被注册")>=0){
                    //找到"该域名未被注册"，说明域名未被注册
                    domain.setStatus(DomainInfo.DOMAIN_STATUS_UNOWNED);
                    System.out.println(domain.getDomainName() + "未注册！");
                }
                else{
                    //否则报错
                    System.err.println("抓取"+domain.getDomainName()+"的WHOIS状态错误");
                }
            }
            for (Element div : css_div_whois){
                String text = div.text();
                if (text.indexOf("访问此网站")>=0){
                    continue;
                }
                if (text.indexOf("正在努力加载更多信息。。")>=0){
                    continue;
                }
                int indexDate = text.indexOf("过期时间：");
                if (indexDate >= 0){
                    //获取过期日期
                    String tmp = text.substring(indexDate);
                    Matcher matcher = PATTERN_DATE.matcher(tmp);
                    if (matcher.find()){
                        String year = matcher.group(3);
                        String month = matcher.group(2);
                        String day = matcher.group(1);
                        String dateString = year+"-"+month+"-"+day;
                        System.out.println(domain.getDomainName()+"的过期日期："+dateString);
                    }
                    else{
                        System.err.println("无法获取到过期日期");
                    }
                }
                //System.out.println(text);
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return true;
    }

    //TODO 获取所有域名
    //搜索条件
    public void getDeletedDomains() throws GankerException{
        int page = 1;
        conf = new SearchConfig();
        conf.setKeyWord("");
        conf.setPosition(SearchConfig.POSITION_ANY);
        conf.setLength(1, 4);
        conf.addComposition(SearchConfig.COMPOSITIONS_ALPHABET);
        conf.setSort(SearchConfig.SORT_ALPHABET);
        conf.addSuffix(SearchConfig.SUFFIX_COM);
        conf.setDeleteType(SearchConfig.STATUS_BOTH);
        conf.setDeleteDate(SearchConfig.DATE_DELETED);
        conf.setPage(page);
        int pageMax = 1;
        try {
            do {
                String html = httpClient.getRequest(DELETED_URL, conf.toPairList());
                //System.out.println(html);
                Document doc = Jsoup.parse(html);

                if (page==1){
                    //获取总页码
                    Elements pagination = doc.select("div.pagination");
                    //System.out.println("选取div数量："+pagination.size());
                    if (pagination.size()==1){
                        Element span = pagination.first().select("span").first();
                        //System.out.println(span.text());
                        //使用正则表达式匹配
                        Matcher matcher = PATTERN_PAGE.matcher(span.text());
                        if (matcher.find()){
                            String pageStr = matcher.group(1);
                            pageMax = Integer.parseInt(pageStr);
                        }
                    }
                }

                System.out.println("正在获取第"+page+"页的域名信息，共"+pageMax+"页");
                Elements tables = doc.select("table#tb_domains");
                if (tables.size() == 1) {
                    Element table = tables.first();
                    //获取tbody
                    Element tbody = table.getElementsByTag("tbody").first();
                    //获取所有tr
                    Elements trs = tbody.select("tr");
                    if (trs.size() == 1) {
                        //TODO 结束获取
                    }
                    for (Element tr : trs) {
                        Elements tds = tr.select("td");
                        String domainName = tds.get(0).text();
                        String deletedDateString = tds.get(3).text();
                        String statusDesc = tds.get(4).text();
                        int status = DomainStatusDesc.get(statusDesc);
                        DomainInfo domainInfo = new DomainInfo(domainName, status, deletedDateString);
                        System.out.println(domainInfo);
                        domains.add(domainInfo);
                    }
                } else {
                    throw new GankerException("错误：无法获取到唯一的id为tb_domains的表格");
                }
                ++page;
                conf.nextPage();
            }
            while (page<=pageMax);

            System.out.println("获取到域名信息"+domains.size()+"个");

        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

    public int checkAll(){
        for (DomainInfo domain : domains){
            String domainName = domain.getDomainName();
            System.out.println("正在检查"+domainName+" ...");
            check(domain);
        }
        return 0;
    }

    public static void main(String[] args) {
        ChinazGanker ganker = new ChinazGanker();
        //ganker.check(new DomainInfo("acigh.com"));
        //ganker.check(new DomainInfo("undsf.com"));
        //ganker.check(new DomainInfo("undsf.org"));
        try {
            ganker.getDeletedDomains();
            ganker.checkAll();
        }
        catch (GankerException e){
            e.printStackTrace();
        }
    }
}
